package main

var ch = make(chan struct{}, 10) // buffered或者unbuffered
var s string

var chUnbuffered = make(chan struct{})
var sUnbuffered string

// main
//
//	@Description: channel的happens-before
func main() {
	//rule01() //【第n次发送Send】 happens-before 【第n次接收完成】	[buffered/unbuffered]
	//rule02() //【关闭Channel】 happens-before 【任何后续的接收操作】 [buffered/unbuffered]
	//rule03() //【第n次接收】 happens-before【 第n次发送完成】  [非缓冲channel]
	//rule04() //【第n次接收】 happens-before 【第n+m次发送完成】 [缓冲channel]

}

// rule01
//
//	@Description:  【第n次发送Send】 happens-before 【第n次接收完成】	[buffered/unbuffered]
func rule01() {
	go f01()
	<-ch
	print(s)
}
func f01() {
	s = "hello, world"
	ch <- struct{}{}
}

// rule02
//
//	@Description: 【关闭Channel】 happens-before 【任何后续的接收操作】 [buffered/unbuffered]
func rule02() {
	go f02()
	<-ch
	print(s)
}
func f02() {
	s = "hello, world"
	//ch <- struct{}{}
	close(ch)
}

// rule03
//
//	@Description: 【第n次接收】 happens-before【 第n次发送完成】  [非缓冲channel]
func rule03() {
	go f03()
	chUnbuffered <- struct{}{}
	print(sUnbuffered)
}

func f03() {
	sUnbuffered = "hello, world"
	<-chUnbuffered
}

// rule04
//
//	@Description:【第n次接收】 happens-before 【第n+m次发送完成】 [缓冲channel]
func rule04() {
	//缓冲型channel，容量为m，第n+m个send发送之后的情形：
	//如果第n个receive还没发生，这时候channel填满了，send就会被阻塞，
	//当第n个receive接收完成后，sender goroutine会被唤醒，之后在继续发送过程
	//也就是说第n个receive happened-before 第n+m个send finished
}
